package cn.bob.pet.service.impl;

import cn.bob.basic.config.BussinessException;
import cn.bob.basic.dto.Point;
import cn.bob.basic.utils.*;
import cn.bob.order.domain.OrderPetAcquisition;
import cn.bob.order.domain.OrderPetAcquisitionLog;
import cn.bob.order.mapper.OrderPetAcquisitionLogMapper;
import cn.bob.order.mapper.OrderPetAcquisitionMapper;
import cn.bob.org.domain.Employee;
import cn.bob.org.domain.Shop;
import cn.bob.pet.domain.PetType;
import cn.bob.pet.dto.HandleDto;
import cn.bob.org.mapper.EmployeeMapper;
import cn.bob.org.mapper.ShopMapper;
import cn.bob.pet.domain.SearchMasterMsg;
import cn.bob.pet.domain.SearchMasterMsgAuditLog;
import cn.bob.pet.mapper.PetTypeMapper;
import cn.bob.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.bob.pet.mapper.SearchMasterMsgMapper;
import cn.bob.pet.query.SearchMasterMsgQuery;
import cn.bob.pet.service.ISearchMasterMsgService;
import cn.bob.basic.service.impl.BaseServiceImpl;
import cn.bob.user.domain.User;
import cn.bob.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.config.RocketMQConfigUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer MsgTimeout;

    private static final Integer THREEDAY=30*1000;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        //写入到数据库修改状态为待审核0  默认为0
        searchMasterMsg.setPetType(1L);
        searchMasterMsgMapper.add(searchMasterMsg);
        //非空校验
        notNullCheck(searchMasterMsg);
        //百度ai校验
        baiduAiCheck(searchMasterMsg);
        //查询方圆50公里的店铺 有就修改店铺id没有就不管
        List<Shop> all = shopMapper.findAll();
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        Shop shop = DistanceUtil.getNearestShop(point, all);
        if (shop!=null){
            searchMasterMsg.setShopId(shop.getId());
            searchMasterMsgMapper.update(searchMasterMsg);
        }
        return AjaxResult.me().success();
    }

    /**
     * 查询待处理的请求的数据
     * @param searchMasterMsg
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery searchMasterMsg) {
        //查询总条数totels
            //根据查询的state查询总条数
        Integer totels= searchMasterMsgMapper.findByState(searchMasterMsg);
         List<SearchMasterMsg> searchMasterMsgPageList = searchMasterMsgMapper.selectSearchMasterMsg(searchMasterMsg);
         //获取店铺用户和类型
         searchMasterMsgPageList.forEach(search->{
             PetType petType = petTypeMapper.findById(search.getPetType());
             User user = userMapper.findById(search.getUserId());
             Shop shop = shopMapper.findById(search.getShopId());
             search.setUserit(user);
             search.setPetTypeit(petType);
             search.setShopit(shop);
         });
        //查询当前页显示值
        return new PageList<SearchMasterMsg>(searchMasterMsgPageList,totels);
    }

    /**
     * 数据的接收订单的操作
     * @param handleDto
     */
    @Override
    public void accept(HandleDto handleDto,Employee employee) {
        //非空校验
        if (handleDto.getHandler()==null || handleDto.getNote() == null){
            throw new BussinessException("参数不能为空！！");
        }
        if (employee==null){
            throw new BussinessException("用户未登录！！");
        }
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(handleDto.getMsgId());
        //加锁
        synchronized (handleDto.getMsgId()){
            if (searchMasterMsg.getState()==1 && employee.getShopId().equals(searchMasterMsg.getShopId())){
                //修改订单状态为已接单 2
                searchMasterMsg.setState(2);
//
                searchMasterMsgMapper.update(searchMasterMsg);
            }
        };
        // 生成收购单
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(handleDto.getMsgId()));
        orderPetAcquisition.setDigest(handleDto.getNote());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis()+THREEDAY));
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(employee.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionMapper.add(orderPetAcquisition);

        //设置延时时间为三十秒等级为3   创建的数据30秒内未处理就直接取消
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
                SendResult sendResult = rocketMQTemplate.syncSend("queue_test_topic", MessageBuilder.withPayload(orderPetAcquisition.getId()).build(), MsgTimeout, 4);
                System.out.println("发送成功了");
//            }
//        });

    }

    /**
     * 拒单
     * @param msgId
     */
    @Override
    public void reject(Long msgId, Employee employee) {
        if (msgId==null){
            throw new BussinessException("参数不能为空！！");
        }
        //将店铺id置为null
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        searchMasterMsg.setShopId(null);
        searchMasterMsg.setState(1);
        searchMasterMsgMapper.update(searchMasterMsg);
        //todo 写入拒单日志

    }

    /**
     * 待审核页面  数据发布
     * @param searchMasterMsg
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toAudit(SearchMasterMsgQuery searchMasterMsg) {
        if (searchMasterMsg.getShopId()!=null){
            throw new BussinessException("当前登录者不是平台管理员没权限");
        }
        //查询总条数totels
        //根据查询的state查询总条数
        Integer totels= searchMasterMsgMapper.findByState(searchMasterMsg);
        List<SearchMasterMsg> searchMasterMsgPageList = searchMasterMsgMapper.selectSearchMasterMsg(searchMasterMsg);
       //需要的用户和品种信息
        searchMasterMsgPageList.forEach(search->{
            PetType petType = petTypeMapper.findById(search.getPetType());
            User user = userMapper.findById(search.getUserId());
            search.setUserit(user);
            search.setPetTypeit(petType);
        });


        //查询当前页显示值
        return new PageList<SearchMasterMsg>(searchMasterMsgPageList,totels);
    }
    /**
     * 寻主池
     * @param searchMasterMsg
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> pool(SearchMasterMsgQuery searchMasterMsg) {
        if (searchMasterMsg.getShopId()!=null){
            throw new BussinessException("当前登录者不是平台管理员没权限");
        }
        //查询总条数totels
        //根据查询的state查询总条数
        Integer totels= searchMasterMsgMapper.findByState(searchMasterMsg);
        List<SearchMasterMsg> searchMasterMsgPageList = searchMasterMsgMapper.selectSearchMasterMsg(searchMasterMsg);
        //查询当前页显示值
        return new PageList<SearchMasterMsg>(searchMasterMsgPageList,totels);
    }
    /**
     * 完成订单
     * @param searchMasterMsg
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery searchMasterMsg) {
        //查询总条数totels
        //根据查询的state查询总条数
        Integer totels= searchMasterMsgMapper.findByState(searchMasterMsg);
        //查找order订单的状态是1的msg消息
        List<OrderPetAcquisition> all = orderPetAcquisitionMapper.findAll();
        List<Long> msgIds = all.stream().filter(orderPetAcquisition -> orderPetAcquisition.getState() == 1)
                .map(OrderPetAcquisition::getSearchMasterMsgId)
                .collect(Collectors.toList());
        List<SearchMasterMsg> sears = msgIds.stream().map(id -> searchMasterMsgMapper.findById(id)).collect(Collectors.toList());
        //业务添加的user shop pettype数据
        sears.forEach(search->{
            PetType petType = petTypeMapper.findById(search.getPetType());
            User user = userMapper.findById(search.getUserId());
            Shop shop = shopMapper.findById(search.getShopId());
            search.setUserit(user);
            search.setPetTypeit(petType);
            search.setShopit(shop);
        });

        //查询当前页显示值
        return new PageList<SearchMasterMsg>(sears,totels);
    }


    //百度ai校验
    private void baiduAiCheck(SearchMasterMsg searchMasterMsg) {
        StringBuilder sb = new StringBuilder();
        sb.append(searchMasterMsg.getName()).append(searchMasterMsg.getAddress());
        if (!BaiduAuditUtils.TextCensor(sb.toString())){
            //失败写填入审核日志 前端跳入到个人中心然后再重新修改
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote(searchMasterMsg.getNote());
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            throw new BussinessException("宠物的名字或地址违规，请在个人中心重新修改！！！");
        }
    }
    //非空校验
    private void notNullCheck(SearchMasterMsg searchMasterMsg) {
        if (StringUtils.isBlank(searchMasterMsg.getName()) || StringUtils.isBlank(searchMasterMsg.getAddress())){
            throw new BussinessException("参数不能为空，请在个人中心重新修改！！！");
        }
    }
}
